import { defineStore } from 'pinia'
import type { TaskGroup } from '../types/group'
import { createTaskGroup as createTaskGroupApi, getTaskGroups as getTaskGroupsApi, updateTaskGroup as updateTaskGroupApi, deleteTaskGroup as deleteTaskGroupApi } from '../services/groupService'

interface GroupState {
  groups: TaskGroup[]
  currentGroupId: number | null
}

export const useGroupStore = defineStore('group', {
  state: (): GroupState => ({
    groups: [],
    currentGroupId: null
  }),

  getters: {
    // 获取所有分组
    getAllGroups: (state) => state.groups,
    
    // 获取默认分组
    getDefaultGroup: (state) => state.groups.find(group => group.is_default),
    
    // 获取当前选中的分组
    getCurrentGroup: (state) => {
      if (state.currentGroupId) {
        return state.groups.find(group => group.group_id === state.currentGroupId)
      }
      return state.groups.length > 0 ? state.groups[0] : null
    },
    
    // 根据ID获取分组
    getGroupById: (state) => (groupId: number) => {
      return state.groups.find(group => group.group_id === groupId)
    }
  },

  actions: {
    // 设置当前分组
    setCurrentGroup(groupId: number) {
      this.currentGroupId = groupId
    },

    // 获取任务分组列表
    async fetchGroups() {
      try {
        console.log('Fetching groups...')
        const response: any = await getTaskGroupsApi()
        console.log('=== ACTUAL GROUP API RESPONSE ===', JSON.stringify(response, null, 2))
        
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { list: [...] } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        let groupsData = []
        
        // 如果response是对象且包含list数组
        if (response && response.success && response.data && response.data.list && Array.isArray(response.data.list)) {
          groupsData = response.data.list
          console.log('Groups data (standard format):', groupsData)
        }
        // 如果response本身就是数组
        else if (response && response.success && Array.isArray(response.data)) {
          groupsData = response.data
          console.log('Groups data (direct array format):', groupsData)
        }
        // 如果是其他格式
        else {
          console.log('Unknown group data format, setting empty array')
          groupsData = []
        }
        
        this.groups = groupsData
        console.log('Final groups data:', this.groups)
        
        // 如果当前没有选中分组，且有分组数据，则默认选中第一个
        if (!this.currentGroupId && this.groups.length > 0 && this.groups[0]) {
          this.currentGroupId = this.groups[0].group_id || null
          console.log('Current group ID set to:', this.currentGroupId)
        }
        
        return { success: true, message: response.message || '获取分组列表成功' }
      } catch (error: any) {
        console.error('Error fetching groups:', error)
        this.groups = []
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else {
          return { success: false, message: error.message || '获取分组列表失败' }
        }
      }
    },

    // 创建任务分组
    async createGroup(name: string) {
      try {
        const response: any = await createTaskGroupApi({ name })
        console.log('Create group API response:', response)
        
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { group_id: ..., name: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.group_id) {
          const groupData = response.data
          this.groups.push(groupData)
          return { success: true, message: response.message || '创建分组成功', data: groupData }
        } else {
          console.log('Invalid group creation response format:', response)
          return { success: false, message: response?.message || '创建分组失败' }
        }
      } catch (error: any) {
        console.error('Error creating group:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else {
          return { success: false, message: error.message || '创建分组失败' }
        }
      }
    },

    // 更新任务分组
    async updateGroup(groupId: number, name: string) {
      try {
        const response: any = await updateTaskGroupApi(groupId, { name })
        console.log('Update group API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { group_id: ..., name: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.group_id) {
          const groupData = response.data
          const index = this.groups.findIndex(group => group.group_id === groupId)
          if (index !== -1) {
            this.groups[index] = groupData
          }
          return { success: true, message: response.message || '更新分组成功', data: groupData }
        } else {
          return { success: false, message: response?.message || '更新分组失败' }
        }
      } catch (error: any) {
        console.error('Error updating group:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '分组不存在' }
        } else {
          return { success: false, message: error.message || '更新分组失败' }
        }
      }
    },

    // 删除任务分组
    async deleteGroup(groupId: number) {
      try {
        const response: any = await deleteTaskGroupApi(groupId)
        console.log('Delete group API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: {} }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success) {
          this.groups = this.groups.filter(group => group.group_id !== groupId)
          
          // 如果删除的是当前选中的分组，则重置当前分组
          if (this.currentGroupId === groupId) {
            this.currentGroupId = this.groups.length > 0 ? this.groups[0]?.group_id || null : null
          }
          
          return { success: true, message: response.message || '删除分组成功' }
        } else {
          return { success: false, message: response?.message || '删除分组失败' }
        }
      } catch (error: any) {
        console.error('Error deleting group:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '分组不存在' }
        } else {
          return { success: false, message: error.message || '删除分组失败' }
        }
      }
    }
  }
})